package com.gx.smart.building.ui.maintain.fragment

import android.content.Intent
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.TimeUtils
import com.gx.smart.base.BaseAdapter
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentMaintainTaskComplete2Binding
import com.gx.smart.building.ui.common.popwindow.RegionPopWindow
import com.gx.smart.building.ui.inspection.event.TaskCompleteEvent
import com.gx.smart.building.ui.maintain.MaintainTaskCompleteDetailActivity
import com.gx.smart.building.ui.maintain.adapter.TaskRecordAdapter
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskAssetDto
import com.huishi.gx.ib.grpc.lib.sysuser.sysregionapi.SysRegionDto
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import razerdp.basepopup.QuickPopupBuilder
import razerdp.basepopup.QuickPopupConfig

class MaintainTaskCompleteFragment2 : CommonFragment(),
    View.OnClickListener,
    TextView.OnEditorActionListener,
    BaseAdapter.OnItemClickListener<PlanTaskAssetDto> {
    private lateinit var viewBinding: FragmentMaintainTaskComplete2Binding
    private lateinit var adapter: TaskRecordAdapter
    private var areaId: String? = null
    private var regionList: List<SysRegionDto>? = null

    override fun onItemClick(e: PlanTaskAssetDto, position: Int) {
        val intent = Intent(requireActivity(), MaintainTaskCompleteDetailActivity::class.java)
        intent.putExtra("planTaskId", e.planTaskId)
        intent.putExtra("assetId", e.assetId)
        startActivity(intent)
    }

    override fun onBindLayout(): Int = R.layout.fragment_maintain_task_complete2

    override fun initContentView(root: ViewGroup) {
        viewBinding = FragmentMaintainTaskComplete2Binding.inflate(layoutInflater, root, true)
        viewBinding.search.setOnEditorActionListener(this)
        viewBinding.clear.setOnClickListener(this)
        viewBinding.filter.setOnClickListener {
            QuickPopupBuilder.with(context)
                .contentView(R.layout.inspection_task_popwindow_layout)
                .config(
                    QuickPopupConfig()
                        .gravity(Gravity.BOTTOM or Gravity.CENTER_VERTICAL)
                        .withClick(
                            R.id.all,
                            { v1: View? ->
                                all()
                            }, true
                        )
                        .withClick(
                            R.id.area,
                            { v1: View? ->
                                areaPicker()
                            }, true
                        )
                )
                .show(it)
        }
    }

    private fun all() {
        this.areaId = ""
        viewBinding.filterContent.text = ""
        if (this::viewBinding.isInitialized) {
            viewBinding.refreshLayout.autoRefresh()
        }
    }

    private fun areaPicker() {
        RegionPopWindow(requireContext())
            .setOnItemSelectedListener { areaId, areaName ->
                this.areaId = areaId
                viewBinding.filterContent.text = areaName
                if (this::viewBinding.isInitialized) {
                    viewBinding.refreshLayout.autoRefresh()
                }
            }.setData(regionList)
            .setBackground(requireContext().getDrawable(R.drawable.background_color))
            .setPopupGravity(Gravity.BOTTOM)
            .showPopupWindow()
    }


    override fun initContent() {
        super.initContent()
        adapter = TaskRecordAdapter(activity)
        adapter.setItemClickListener(this)
        initView(viewBinding.recyclerView, adapter, viewBinding.refreshLayout)
    }

    override fun doAction() {
        requireActivity().intent.getStringExtra("id")?.let {
            viewModel.queryPlanTaskAssetList(currentPage, 1, it, keyword ?: "", areaId ?: "")
                .observe(viewLifecycleOwner) { list ->
                    handleResult(list)
                }
        }
    }

    override fun initData() {
        super.initData()
        doAction()
        registerEventBus()
        viewModel.sysRegionQuery().observe(viewLifecycleOwner) {
            regionList = it
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun handleEvent(event: TaskCompleteEvent) {
        viewBinding.planName.text = event.item.planName
        viewBinding.taskCode.text = "任务编号：${event.item.taskCode}"
        val validTime = TimeUtils.millis2String(event.item.validTime, "yyyy-MM-dd HH:mm")
        val invalidTime = TimeUtils.millis2String(event.item.invalidTime, "yyyy-MM-dd HH:mm")
        viewBinding.time.text =
            "执行时间：$validTime-$invalidTime" //执行时间：2022-05-01 12:00 — 2022-05-10 12:00
        viewBinding.deviceTotal.text = "保养设备数量: ${event.item.deviceTotal}"
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            search()
            KeyboardUtils.hideSoftInput(v!!)
            return true
        }
        return false
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.clear -> viewBinding.search.editableText.clear()
        }
    }

    private fun search() {
        val name = viewBinding.search.text.toString().trim()
        search(name)
    }

    override fun search(keyword: String?) {
        super.search(keyword)
        if (this::viewBinding.isInitialized) {
            viewBinding.refreshLayout.autoRefresh()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterEventBus()
    }


    companion object {
        @JvmStatic
        fun newInstance() = MaintainTaskCompleteFragment2()
    }
}